package com.jkj.http.sys.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpSession;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.jkj.http.entity.ZTreeNode;
import com.jkj.http.sys.dao.SysPermissionDao;
import com.jkj.http.sys.dao.SysRoleAuthorizeDao;
import com.jkj.http.sys.entity.SysPermission;
import com.jkj.http.sys.entity.SysRoleAuthorize;
import com.jkj.http.sys.service.RoleAuthorizeService;
import com.jkj.utils.OperatorProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class RoleAuthorizeServiceImp implements RoleAuthorizeService {
    @Autowired
    private SysRoleAuthorizeDao roleAuthorizeDao;
    @Autowired
    private SysPermissionDao permissionDao;

    @Override
    @Transactional
    public void authorize(HttpSession session, String roleId, String[] perIdArray) {
        // 角色原有的授权信息。
        List<SysRoleAuthorize> listOldPers = roleAuthorizeDao.getList(roleId);
        for (SysRoleAuthorize item : listOldPers) {
            roleAuthorizeDao.delete(item.getId());
        }
        // 新增新的权限
        for (String moduleId : perIdArray) {
            SysRoleAuthorize item = new SysRoleAuthorize();
            item.setId(IdUtil.simpleUUID());
            item.setRoleId(roleId);
            item.setModuleId(moduleId);
            item.setCreateTime(DateUtil.date());
            item.setCreateUser(OperatorProvider.getCurrent(session).getAccount());
            roleAuthorizeDao.insert(item);
        }
    }

    @Override
    public List<ZTreeNode> getZTreeNode(String roleId) {
        List<SysRoleAuthorize> sysRoleAuthorizeList = roleAuthorizeDao.getList(roleId);
        List<String> listPerIds = new ArrayList<String>();
        for (SysRoleAuthorize item : sysRoleAuthorizeList) {
            if (!listPerIds.contains(item.getModuleId()))
                listPerIds.add(item.getModuleId());
        }
        List<SysPermission> listAllPers = permissionDao.getPermissionList();
        List<ZTreeNode> result = new ArrayList<ZTreeNode>();
        for (SysPermission item : listAllPers) {
            ZTreeNode model = new ZTreeNode();
            model.setChecked(listPerIds.contains(item.getId()) ? true : false);
            model.setId(item.getId());
            model.setpId(item.getParentId());
            model.setName(item.getName());
            model.setOpen(true);
            result.add(model);
        }
        return result;
    }

}
